import '../scss/collections.scss'

import Header from '../components/header'
import NewsItem from '../components/news_item'
import NoContentTip from '../components/no_content_tip'

import tools from '../utils/tools'

const header = new Header(),
      newsItem = new NewsItem(),
      noContentTip = new NoContentTip();

const App = ($, win) => {
  const $app = $('#app'),
        $list = $app.children('.list'),
        collections = JSON.parse(localStorage.getItem('collections'));

  const init = () => {
    render();
  }

  const render = () => {
    _renderHeader();

    if (!collections || Object.keys(collections).length === 0) {
      // 没有新闻
      console.log('没有收藏新闻');
      _renderNoContentTip('没有收藏新闻');
    } else {
      _renderNewsList(collections);
    }

    bindEvent();
  }

  const bindEvent = () => {
    $list.on('click', '.news-item', toDetailPage);
  }

  const _renderHeader = () => {
    $app.append(header.tpl({
      title: '新闻详情',
      showLeftIcon: true,
      showRightIcon: false
    }))
  }

  const _renderNewsList = (data) => {
    $list.append(newsItem.tpl(_arrangDatas(data)));
    tools.thumbShow($('.news-thumb'));
  }

  const _renderNoContentTip = (text) => {
    $app.append(noContentTip.tpl(text));
  }

  const _arrangDatas = (data) => {
    let _arr = [];

    for (let key in data) {
      _arr.push(data[key]);
    }
    return _arr;
  }

  function toDetailPage () {
    const $this = $(this),
          url = $this.attr('data-url'),
          uniquekey = $this.attr('data-uniquekey');

    localStorage.setItem('target', JSON.stringify(collections[uniquekey]));
    window.location.href = `detail.html?news_url=${url}&uniquekey=${uniquekey}`;
  }

  init();
}

App(Zepto, window);